import { TradeOffer, TradeStatus, GameState, Player, GameError, GameErrorType, TradeItem } from '../types';

export class TradeManager {
  /**
   * 创建交易提案
   */
  createTradeOffer(
    from: string,
    to: string,
    offering: TradeItem[],
    requesting: TradeItem[],
    gameState: GameState
  ): string {
    // 验证玩家存在
    const fromPlayer = gameState.players.find(p => p.id === from);
    const toPlayer = gameState.players.find(p => p.id === to);

    if (!fromPlayer || !toPlayer) {
      throw new GameError(GameErrorType.INVALID_TRADE, '玩家不存在');
    }

    if (from === to) {
      throw new GameError(GameErrorType.INVALID_TRADE, '不能与自己交易');
    }

    // 验证交易内容
    if (!this.validateTradeItems(offering, fromPlayer, gameState)) {
      throw new GameError(GameErrorType.INVALID_TRADE, '提供的物品无效');
    }

    if (!this.validateTradeItems(requesting, toPlayer, gameState)) {
      throw new GameError(GameErrorType.INVALID_TRADE, '请求的物品无效');
    }

    // 创建交易
    const tradeId = `trade-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    const trade: TradeOffer = {
      id: tradeId,
      from,
      to,
      offering,
      requesting,
      status: TradeStatus.PENDING,
      timestamp: Date.now(),
    };

    gameState.tradeOffers.push(trade);

    return tradeId;
  }

  /**
   * 验证交易物品
   */
  private validateTradeItems(items: TradeItem[], player: Player, gameState: GameState): boolean {
    for (const item of items) {
      if (item.type === 'money') {
        if (!item.amount || item.amount <= 0) {
          return false;
        }
        if (player.money < item.amount) {
          return false;
        }
      } else if (item.type === 'property') {
        if (!item.id) {
          return false;
        }
        if (!player.properties.includes(item.id)) {
          return false;
        }
        // 检查地块是否有建筑物
        const property = gameState.board.find(s => s.property?.id === item.id)?.property;
        if (property && property.level > 0) {
          return false; // 有建筑物的地块不能交易
        }
      } else if (item.type === 'item') {
        if (!item.id) {
          return false;
        }
        if (!player.items.find(i => i.id === item.id)) {
          return false;
        }
      }
    }
    return true;
  }

  /**
   * 验证交易
   */
  validateTrade(tradeId: string, gameState: GameState): boolean {
    const trade = gameState.tradeOffers.find(t => t.id === tradeId);
    if (!trade) {
      return false;
    }

    const fromPlayer = gameState.players.find(p => p.id === trade.from);
    const toPlayer = gameState.players.find(p => p.id === trade.to);

    if (!fromPlayer || !toPlayer) {
      return false;
    }

    // 重新验证双方资源
    return this.validateTradeItems(trade.offering, fromPlayer, gameState) &&
           this.validateTradeItems(trade.requesting, toPlayer, gameState);
  }

  /**
   * 接受交易
   */
  acceptTrade(tradeId: string, gameState: GameState): boolean {
    const trade = gameState.tradeOffers.find(t => t.id === tradeId);
    if (!trade) {
      throw new GameError(GameErrorType.INVALID_TRADE, '交易不存在');
    }

    if (trade.status !== TradeStatus.PENDING) {
      throw new GameError(GameErrorType.INVALID_TRADE, '交易已处理');
    }

    // 验证交易仍然有效
    if (!this.validateTrade(tradeId, gameState)) {
      throw new GameError(GameErrorType.INVALID_TRADE, '交易无效');
    }

    // 执行交易
    this.executeTrade(tradeId, gameState);
    trade.status = TradeStatus.ACCEPTED;

    // 记录到历史
    gameState.history.push({
      id: `event-${Date.now()}`,
      type: 'trade',
      playerId: trade.from,
      description: `${trade.from} 与 ${trade.to} 完成交易`,
      timestamp: Date.now(),
      data: trade,
    });

    return true;
  }

  /**
   * 拒绝交易
   */
  rejectTrade(tradeId: string, gameState: GameState): void {
    const trade = gameState.tradeOffers.find(t => t.id === tradeId);
    if (!trade) {
      throw new GameError(GameErrorType.INVALID_TRADE, '交易不存在');
    }

    if (trade.status !== TradeStatus.PENDING) {
      throw new GameError(GameErrorType.INVALID_TRADE, '交易已处理');
    }

    trade.status = TradeStatus.REJECTED;
  }

  /**
   * 修改交易
   */
  modifyTrade(tradeId: string, changes: Partial<TradeOffer>, gameState: GameState): void {
    const trade = gameState.tradeOffers.find(t => t.id === tradeId);
    if (!trade) {
      throw new GameError(GameErrorType.INVALID_TRADE, '交易不存在');
    }

    if (trade.status !== TradeStatus.PENDING) {
      throw new GameError(GameErrorType.INVALID_TRADE, '交易已处理');
    }

    // 只允许修改提供和请求的物品
    if (changes.offering) {
      const fromPlayer = gameState.players.find(p => p.id === trade.from);
      if (!fromPlayer || !this.validateTradeItems(changes.offering, fromPlayer, gameState)) {
        throw new GameError(GameErrorType.INVALID_TRADE, '修改后的提供物品无效');
      }
      trade.offering = changes.offering;
    }

    if (changes.requesting) {
      const toPlayer = gameState.players.find(p => p.id === trade.to);
      if (!toPlayer || !this.validateTradeItems(changes.requesting, toPlayer, gameState)) {
        throw new GameError(GameErrorType.INVALID_TRADE, '修改后的请求物品无效');
      }
      trade.requesting = changes.requesting;
    }

    trade.timestamp = Date.now();
  }

  /**
   * 执行交易
   */
  executeTrade(tradeId: string, gameState: GameState): void {
    const trade = gameState.tradeOffers.find(t => t.id === tradeId);
    if (!trade) {
      throw new GameError(GameErrorType.INVALID_TRADE, '交易不存在');
    }

    const fromPlayer = gameState.players.find(p => p.id === trade.from);
    const toPlayer = gameState.players.find(p => p.id === trade.to);

    if (!fromPlayer || !toPlayer) {
      throw new GameError(GameErrorType.INVALID_TRADE, '玩家不存在');
    }

    // 转移提供的物品（from -> to）
    this.transferItems(trade.offering, fromPlayer, toPlayer, gameState);

    // 转移请求的物品（to -> from）
    this.transferItems(trade.requesting, toPlayer, fromPlayer, gameState);
  }

  /**
   * 转移物品
   */
  private transferItems(items: TradeItem[], from: Player, to: Player, gameState: GameState): void {
    for (const item of items) {
      if (item.type === 'money' && item.amount) {
        from.money -= item.amount;
        to.money += item.amount;
      } else if (item.type === 'property' && item.id) {
        // 移除from的地块
        const index = from.properties.indexOf(item.id);
        if (index !== -1) {
          from.properties.splice(index, 1);
        }
        
        // 添加到to的地块
        to.properties.push(item.id);
        
        // 更新地块所有者
        const property = gameState.board.find(s => s.property?.id === item.id)?.property;
        if (property) {
          property.owner = to.id;
        }
      } else if (item.type === 'item' && item.id) {
        // 移除from的道具
        const itemIndex = from.items.findIndex(i => i.id === item.id);
        if (itemIndex !== -1) {
          const removedItem = from.items.splice(itemIndex, 1)[0];
          to.items.push(removedItem);
        }
      }
    }
  }

  /**
   * 获取玩家的待处理交易
   */
  getPendingTrades(playerId: string, gameState: GameState): TradeOffer[] {
    return gameState.tradeOffers.filter(
      t => (t.from === playerId || t.to === playerId) && t.status === TradeStatus.PENDING
    );
  }

  /**
   * 取消交易
   */
  cancelTrade(tradeId: string, gameState: GameState): void {
    const tradeIndex = gameState.tradeOffers.findIndex(t => t.id === tradeId);
    if (tradeIndex !== -1) {
      gameState.tradeOffers.splice(tradeIndex, 1);
    }
  }

  /**
   * 清理已完成的交易
   */
  cleanupCompletedTrades(gameState: GameState): void {
    gameState.tradeOffers = gameState.tradeOffers.filter(
      t => t.status === TradeStatus.PENDING
    );
  }
}

// 导出单例实例
export const tradeManager = new TradeManager();
